package com.gjy.util.steam;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-10-23 10:05:18
 */
public class StreamUtil {

    /**
     * 去重集合中的数据
     *
     * @param list  待去重集合
     * @param cls   集合泛型类型
     * @param field 泛型类型的字段, 仅支持 Integer,Long,String
     * @param <T>   任意类型
     * @return 去重后的集合
     */
    public static <T> List<T> distinct(List<T> list, Class<T> cls, String field) {
        try {
            Field f = cls.getDeclaredField(field);
            f.setAccessible(true);
            Class<?> type = f.getType();

            if (type == Long.class) {
                return list.stream().collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparingLong(
                                s -> {
                                    try {
                                        return (Long) f.get(s);
                                    } catch (Exception e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                        ))),
                        ArrayList::new
                ));
            } else if (type == Integer.class) {
                return list.stream().collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparingInt(
                                s -> {
                                    try {
                                        return (Integer) f.get(s);
                                    } catch (Exception e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                        ))),
                        ArrayList::new
                ));
            } else {
                return list.stream().collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(
                                s -> {
                                    try {
                                        return (String) f.get(s);
                                    } catch (Exception e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                        ))),
                        ArrayList::new
                ));
            }
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }
}
